package com.dzdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzdp.dto.Result;
import com.dzdp.entity.ShopType;
import com.dzdp.mapper.ShopTypeMapper;
import com.dzdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.dzdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.dzdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yozi
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result listShopType() {
        // 1.尝试查询Redis缓存
        String shopTypesJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        // 2.判断是否命中缓存
        if (StrUtil.isNotBlank(shopTypesJson)) {
            // 3.存在，返回
            List<ShopType> typeList = JSONUtil.toList(shopTypesJson, ShopType.class);
            return Result.ok(typeList);
        }
        // 4.不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 5.判断数据库是否存在数据
        if (typeList == null) {
            // 6.不存在，返回错误信息
            Result.fail("类别信息为空！");
        }
        // 7.存在，写入Redis缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(typeList));
        stringRedisTemplate.expire(CACHE_SHOP_TYPE_KEY, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        // 8.返回数据
        return Result.ok(typeList);
    }
}
